package com.leather.admin.controller;

import com.google.common.collect.Maps;
import com.leather.admin.entity.Role;
import com.leather.admin.service.AdminService;
import com.leather.admin.service.RoleService;
import com.leather.admin.vo.AdminRoleVo;
import com.leather.admin.vo.AdminVo;
import com.leather.common.result.CodeMsg;
import com.leather.common.result.Result;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RequestMapping("/admin/user")
@Controller
public class WorkerController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;

    @GetMapping("/index")
    @RequiresPermissions("admin:user:index")
    public String index(){
        return "admin/index";
    }

    @GetMapping("/list")
    @RequiresPermissions("admin:user:index")
    @ResponseBody
    public  Object list (){
        Map<String,Object> maps = Maps.newHashMap();
        List<AdminRoleVo> admin = adminService.getAdmin();
        maps.put("rows",admin);
        maps.put("total",admin.size());
        return maps;
    }

    @GetMapping("/create")
    @RequiresPermissions("admin:user:create")
    public String create(Model model){
        List<Role> roles =roleService.list();
        model.addAttribute("roles",roles);
        return "admin/create";
    }

    @PostMapping("/create")
    @ResponseBody
    @RequiresPermissions("admin:user:create")
    public Result postCreate(AdminVo adminVo){
       return adminService.addAdmin(adminVo);
    }

    @PostMapping("/delete")
    @ResponseBody
    @RequiresPermissions("admin:user:delete")
    public Result deleteAdmin(@RequestParam("id") int id) {
        if (adminService.removeById(id)) {
            return Result.success("success");
        }
        return Result.error(CodeMsg.SERVER_ERROR);
    }

}
